package PenTest.shizai;

public class Main {
    //volatile int bananas=100;
/*    class  monkey implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {

            return 0;
        }
    }*/

    //每只猴子轮流吃

    private static int bananas=100;

    private static int turn=0;

    private static Object lock=new Object();

    public static void main(String[] args) {
        Thread t1=new Thread(()->alterEat(0));
        Thread t2=new Thread(()->alterEat(1));
        Thread t3=new Thread(()->alterEat(2));
        t1.start();
        t2.start();
        t3.start();
    }

    private static void alterEat(int offset) {
        int eatTotalNum=0;
        while (bananas>0) {
            synchronized (lock) {
                //香蕉要够吃
                while (turn%3!=offset) {//需要多次检查这个条件
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                if(bananas>0&&turn%3==offset) {//够吃
                    int eatNum=generateEatNum();
                    bananas-=eatNum;
                    eatTotalNum+=eatNum;
                    if(bananas<0) {
                        bananas+=eatNum;
                        eatTotalNum-=eatNum;
                    }
                    turn++;
                    lock.notifyAll();
                }
            }
            System.out.println(Thread.currentThread().getName()+" "+eatTotalNum);
        }
    }

    private static int generateEatNum() {
        int val = (int) (Math.random() * 2 + 1);
        return val;
    }

}
